package org.zhaolei.service.sys;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.zhaolei.dto.sys.MenuTreeDTO;
import org.zhaolei.dto.sys.MetaDTO;
import org.zhaolei.entity.MenuConditionEntity;
import org.zhaolei.entity.MenuEntity;
import org.zhaolei.mapper.MenuMapper;

import java.awt.*;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    public List<MenuTreeDTO> getMenuTree() {
        MenuConditionEntity menuConditionEntity = new MenuConditionEntity();
        menuConditionEntity.setPageSize(0);
        menuConditionEntity.setPid(0L);
        List<MenuEntity> menuEntities = menuMapper.searchByCondition(menuConditionEntity);
        if (CollectionUtils.isEmpty(menuEntities)) {
            return Collections.emptyList();
        }

        List<MenuTreeDTO> result = Lists.newArrayList();
        for(MenuEntity menuEntity : menuEntities) {
            MenuTreeDTO menuTreeDTO = buildMenuTreeDTO(menuEntity);
            menuTreeDTO.setAlwaysShow(true);
            result.add(menuTreeDTO);
            buildChildren(menuEntity, menuTreeDTO);
        }
        return result;
    }

    /**
     * 建造子菜单树，没有返回值，就是给入参的MenuTreeDTO添加子菜单
     * @param menuEntity
     * @param menuTreeDTO
     */
    private void buildChildren(MenuEntity menuEntity, MenuTreeDTO menuTreeDTO) {
        MenuConditionEntity menuConditionEntity = new MenuConditionEntity();
        menuConditionEntity.setPageSize(0);
        menuConditionEntity.setPid(menuEntity.getId());
        List<MenuEntity> childrenEntity = menuMapper.searchByCondition(menuConditionEntity);
        if (!CollectionUtils.isEmpty(childrenEntity)) {
            for (MenuEntity childEntity : childrenEntity) {
                MenuTreeDTO childMenuTreeDTO = buildMenuTreeDTO(childEntity);
                menuTreeDTO.addChildren(childMenuTreeDTO);
                buildChildren(childEntity, childMenuTreeDTO);
            }
        }
    }

    private MenuTreeDTO buildMenuTreeDTO(MenuEntity menuEntity) {
        MenuTreeDTO menuTreeDTO = BeanUtil.copyProperties(menuEntity, MenuTreeDTO.class);
        menuTreeDTO.setAlwaysShow( true);
        MetaDTO metaDTO = new MetaDTO();
        menuTreeDTO.setMeta(metaDTO);
        metaDTO.setTitle(menuEntity.getName());
        metaDTO.setIcon(menuEntity.getIcon());
        metaDTO.setNoCache(true);
        return menuTreeDTO;
    }
}
